package com.company.cloud.mall.modules.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.acct.modules.api.constant.AcctOpTypeEnum;
import com.company.cloud.acct.modules.api.constant.AcctTypeEnum;
import com.company.cloud.acct.modules.api.request.AcctOpRequest;
import com.company.cloud.acct.modules.api.service.AccountRemoteService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.company.modules.api.response.CompanySimple;
import com.company.cloud.company.modules.api.service.CompanyRemoteService;
import com.company.cloud.mall.constant.MallErrorEnum;
import com.company.cloud.mall.constant.PayMethodEnum;
import com.company.cloud.mall.constant.ShopConstant.PayActionTypeEnum;
import com.company.cloud.mall.constant.ShopConstant.PayConfirmWay;
import com.company.cloud.mall.modules.api.constant.OrderStateEnum;
import com.company.cloud.mall.modules.app.controller.req.PayResultReportParam;
import com.company.cloud.mall.modules.app.models.PayApplyModel;
import com.company.cloud.mall.modules.app.models.PayResultModel;
import com.company.cloud.mall.modules.app.service.ShopOnlinePayService;
import com.company.cloud.mall.modules.app.service.ShopOrderPayService;
import com.company.cloud.mall.modules.base.entity.OrderInfo;
import com.company.cloud.mall.modules.base.entity.OrderItem;
import com.company.cloud.mall.modules.base.entity.OrderPayment;
import com.company.cloud.mall.modules.base.service.OrderInfoService;
import com.company.cloud.mall.modules.base.service.OrderItemService;
import com.company.cloud.mall.modules.base.service.OrderPaymentService;
import com.company.cloud.mall.modules.bus.producer.ShopOrderProducer;
import com.company.cloud.mall.modules.utils.ShopNoUtils;
import com.company.cloud.pay.modules.api.constant.PayStateEnum;
import com.company.common.server.constant.IRelBusiType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;


@Service
public class ShopOrderPayServiceImpl implements ShopOrderPayService {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderPaymentService orderPaymentService;
    @Autowired
    private AccountRemoteService accountRemoteService;
    @Autowired
    private ShopOnlinePayService shopOnlinePayService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ShopOrderProducer shopOrderProducer;
    @Autowired
    private CompanyRemoteService companyRemoteService;

    /**
     * 支付结果上报
     */
    @Transactional
    @Override
    public void payReport(PayResultReportParam params, PayConfirmWay confirmChannel, LoginSimpleUserInfo userInfo) {

        ValidatorUtils.validate(params);
        if (PayStateEnum.Pay_Success.getCode().equals(params.getState()) ||
                PayStateEnum.Pay_Fail.getCode().equals(params.getState())) {
        } else {
            throw new BusinessException(BaseReturnEnum.PARAM_ERROR);
        }
        OrderPayment payment = orderPaymentService.getOne(new QueryWrapper<OrderPayment>().eq("pay_sn", params.getSn()));
        if (null == payment) {
            throw new BusinessException(MallErrorEnum.Pay_Null);
        }
        if (!PayActionTypeEnum.PA_Pay.getCode().equals(payment.getType())) {
            throw new BusinessException(MallErrorEnum.Pay_Null);
        }
        if (!IRelBusiType.Order_ObjType.equals(payment.getBizOrderType())) {
            throw new BusinessException(MallErrorEnum.Pay_Null);
        }
        if (!PayStateEnum.Pay_Ing.getCode().equals(payment.getPaymentState())) {
            return;
        }
        if (!PayMethodEnum.PM_Online_Pay.getCode().equals(payment.getPaymentMethod())) {
            return;
        }
        if (confirmChannel == PayConfirmWay.User_Confirm) { //用户回调
            PayResultModel payResult = shopOnlinePayService.queryPayResult(payment.getCustNo(), payment.getPaySn(), payment.getPaymentChannel());
            PayResultReportParam payParams = new PayResultReportParam();
            payParams.setSn(params.getSn());
            payParams.setMemo(params.getMemo());
            payParams.setState(payResult.getState());
            payParams.setThirdState(payResult.getThirdState());
            payParams.setThirdMemo(payResult.getThirdMemo());
            this._payReport(payParams, payment.getPaymentMethod(), payment.getPaymentChannel(), PayConfirmWay.ThirdQuery_Confirm, userInfo);
        } else {
            this._payReport(params, payment.getPaymentMethod(), payment.getPaymentChannel(), confirmChannel, userInfo);
        }
    }

    /**
     * 支付结果处理
     */
    private void _payReport(PayResultReportParam params, String paymentMethod, String paymentChannel,
                            PayConfirmWay confirmChannel, LoginSimpleUserInfo userInfo) {
        List<OrderPayment> orderPaymentList = orderPaymentService.list(new QueryWrapper<OrderPayment>().eq("pay_sn", params.getSn()));
        List<OrderPayment> updateOrderPaymentList = new ArrayList<OrderPayment>();
        List<OrderInfo> updateOrderList = new ArrayList<OrderInfo>();
        List<String> orderSns = new ArrayList<String>();
        orderPaymentList.forEach(payment -> {
            payment.setPaymentState(params.getState());
            payment.setPaymentConfirmDate(LocalDateTime.now());
            payment.setMemo(params.getMemo());
            payment.setPaymentConfirmChannel(confirmChannel.getCode());
            payment.setThirdState(params.getThirdState());
            payment.setThirdMemo(params.getThirdMemo());
            updateOrderPaymentList.add(payment);

            orderSns.add(payment.getBizOrderSn());
        });

        Collection<OrderInfo> ordersList = orderInfoService.listByIds(orderSns);
        List<OrderInfo> paySuccessOrderList = new ArrayList<OrderInfo>();
        ordersList.forEach(order -> {
            if (PayStateEnum.Pay_Success.getCode().equals(params.getState())) {
                String companyNo = null;
                if (StringUtils.isEmpty(companyNo)) {
                    companyNo = order.getMainCompanyNo();
                } else {

                }
                order.setStatus(OrderStateEnum.OSE_Send.getCode());
                order.setHandleDate(LocalDateTime.now());
                order.setHandleUserId(userInfo.getId());
                order.setPaymentMethod(paymentMethod);
                if(paymentChannel!=null){
                    if(paymentChannel.equals("ALI_APP") || paymentChannel.equals("ALI_WEB")){
                        order.setPaymentMethod("66");
                    }
                }
                order.setPaymentFee(BigDecimal.ZERO);
                order.setPaymentFund(order.getFund());
                order.setPaymentState(params.getState());
                order.setPayDate(LocalDateTime.now());
                updateOrderList.add(order);
                paySuccessOrderList.add(order);
                //添加余额  Fangjun
                Integer userId = 0;
                BaseClientResult<CompanySimple> companySimple = companyRemoteService.getCompanySimple(companyNo);
                CompanySimple companySimple1 = companySimple.getData();
                if (companySimple1 != null) {
                    if(StringUtils.isEmpty(companySimple1.getUserId())){
                        userId =0;
                    }
                    if(! StringUtils.isEmpty(companySimple1.getUserId())){
                        userId =Integer.valueOf(companySimple1.getUserId());
                    }
                }
                this._payByBalance(companyNo, order.getSn(), userId, order.getFund(), userInfo);

            } else if (PayStateEnum.Pay_Fail.getCode().equals(params.getState())) {
                order.setPaymentState(params.getState());
                order.setPaymentMethod(paymentMethod);
                if(paymentChannel!=null){
                    if(paymentChannel.equals("ALI_APP") || paymentChannel.equals("ALI_WEB")){
                        order.setPaymentMethod("66");
                    }
                }
                order.setPaymentFee(BigDecimal.ZERO);
                order.setPaymentFund(order.getFund());
                order.setPayDate(LocalDateTime.now());
                updateOrderList.add(order);
            } else if (PayStateEnum.Pay_Not.getCode().equals(params.getState())) {
                order.setPaymentState(params.getState());
                order.setPaymentMethod(paymentMethod);
                if(paymentChannel!=null){
                    if(paymentChannel.equals("ALI_APP") || paymentChannel.equals("ALI_WEB")){
                        order.setPaymentMethod("66");
                    }
                }
                order.setPaymentFee(BigDecimal.ZERO);
                order.setPaymentFund(order.getFund());
                order.setPayDate(LocalDateTime.now());
                updateOrderList.add(order);
            }
        });
        if (updateOrderPaymentList.size() > 0) {
            orderPaymentService.updateBatchById(updateOrderPaymentList);
        }
        if (updateOrderList.size() > 0) {
            orderInfoService.updateBatchById(updateOrderList);
        }
        //MQ
        this.onPaySuccessMQ(paySuccessOrderList);
    }

    /**
     * 支付成功MQ通知
     */
    private void onPaySuccessMQ(List<OrderInfo> paySuccessOrders) {
        if (CollectionUtils.isEmpty(paySuccessOrders)) {
            return;
        }
        Set<String> orderNos = new HashSet<String>();
        paySuccessOrders.forEach(item -> {
            orderNos.add(item.getSn());
        });
        List<OrderItem> orderItemList = orderItemService
                .list(new QueryWrapper<OrderItem>().in("order_sn", orderNos));
        Map<String, List<OrderItem>> orderMap = new HashMap<String, List<OrderItem>>();
        orderItemList.forEach(item -> {
            List<OrderItem> orderItems = orderMap.get(item.getOrderSn());
            if (orderItems == null) {
                orderItems = new ArrayList<>();
            }
            orderItems.add(item);
        });

        paySuccessOrders.forEach(order -> {
            System.out.println("支付成功，系统回调 ---- " + JSON.toJSONString(order));
            List<OrderItem> orderItems = orderMap.get(order.getSn());
            if (!CollectionUtils.isEmpty(orderItems)) {
                shopOrderProducer.onOrderChange(order, orderItems);
            }
        });

    }


    /**
     * 检查支付结果任务2
     */
    public void payResultTask2(List<String> orderSn, LoginSimpleUserInfo userInfo) {
        if (CollUtil.isEmpty(orderSn)) {
            return;
        }
        List<OrderPayment> paymentList = orderPaymentService.list(new QueryWrapper<OrderPayment>()
                .select("pay_sn", "payment_channel", "cust_no")
                .eq("payment_state", PayStateEnum.Pay_Ing.getCode())
                .eq("payment_method", PayMethodEnum.PM_Online_Pay.getCode())
                .eq("type", PayActionTypeEnum.PA_Pay.getCode())
                .eq("biz_order_type", IRelBusiType.Order_ObjType)
                .in(CollUtil.isNotEmpty(orderSn), "biz_order_sn", orderSn)
                .groupBy("pay_sn", "payment_channel", "cust_no")
                .last(" LIMIT 0,50 ")
        );
        if (!CollectionUtils.isEmpty(paymentList)) {
            for (OrderPayment payment : paymentList) {
                PayResultModel payResult = shopOnlinePayService.queryPayResult(payment.getCustNo(), payment.getPaySn(), payment.getPaymentChannel());
                PayResultReportParam payParams = new PayResultReportParam();
                payParams.setSn(payment.getPaySn());
                payParams.setMemo("任务查询支付结果");
                payParams.setState(payResult.getState());
                payParams.setThirdState(payResult.getThirdState());
                payParams.setThirdMemo(payResult.getThirdMemo());
                this._payReport(payParams, payment.getPaymentMethod(), payment.getPaymentChannel(), PayConfirmWay.ThirdQuery_Confirm, userInfo);

            }
        }
    }

    /**
     * 检查支付结果任务
     */
    @Override
    public void payResultTask(String orderSn, LoginSimpleUserInfo userInfo) {
        List<OrderPayment> paymentList = orderPaymentService.list(new QueryWrapper<OrderPayment>()
                .select("pay_sn", "payment_channel", "cust_no")
                .eq("payment_state", PayStateEnum.Pay_Ing.getCode())
                .eq("payment_method", PayMethodEnum.PM_Online_Pay.getCode())
                .eq("type", PayActionTypeEnum.PA_Pay.getCode())
                .eq("biz_order_type", IRelBusiType.Order_ObjType)
                .eq(StringUtils.hasText(orderSn), "biz_order_sn", orderSn)
                .le(StringUtils.isEmpty(orderSn), "payment_apply_date", LocalDateTime.now().plusMinutes(-3))
                .groupBy("pay_sn", "payment_channel", "cust_no")
                .last(" LIMIT 0,50 ")
        );
        if (!CollectionUtils.isEmpty(paymentList)) {
            for (OrderPayment payment : paymentList) {
                PayResultModel payResult = shopOnlinePayService.queryPayResult(payment.getCustNo(), payment.getPaySn(), payment.getPaymentChannel());
                PayResultReportParam payParams = new PayResultReportParam();
                payParams.setSn(payment.getPaySn());
                payParams.setMemo("任务查询支付结果");
                payParams.setState(payResult.getState());
                payParams.setThirdState(payResult.getThirdState());
                payParams.setThirdMemo(payResult.getThirdMemo());
                this._payReport(payParams, payment.getPaymentMethod(), payment.getPaymentChannel(), PayConfirmWay.ThirdQuery_Confirm, userInfo);

            }
        }
    }


    /**
     * 线上第三方支付（单订单）
     */
    @Transactional
    @Override
    public PayApplyModel thirdPay(String sn, String paymentChannel, String returnUrl, LoginSimpleUserInfo userInfo) {

        if (StringUtils.isEmpty(sn)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }

//		OrderInfo order= orderInfoService.getById(sn);
//		if(PayStateEnum.Pay_Ing.getCode().equals(order.getPaymentState())) {
//			this.payResultTask(sn, userInfo);
//		}

        this.payResultTask(sn, userInfo);
        List<String> sns = new ArrayList<String>();
        sns.add(sn);
        return this.thirdPay(sns, IRelBusiType.Order_ObjType, userInfo, paymentChannel, returnUrl);
    }

    /**
     * 线上第三方支付（多订单）
     */
    @Transactional
    @Override
    public PayApplyModel thirdPay(List<String> sns, String paymentChannel, String returnUrl, LoginSimpleUserInfo userInfo) {
        if (CollectionUtils.isEmpty(sns)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        this.payResultTask2(sns, userInfo);
        return this.thirdPay(sns, IRelBusiType.Order_ObjType, userInfo, paymentChannel, returnUrl);
    }

    /**
     * 线上第三方支付
     */
    private PayApplyModel thirdPay(List<String> sns, String bizOrderType, LoginSimpleUserInfo userInfo,
                                   String paymentChannel, String returnUrl) {


        List<OrderInfo> orderList = orderInfoService.listByIds(sns);
//		List<OrderInfo> orderList= orderInfoService.list(new QueryWrapper<OrderInfo>().in("sn", sns));

//		List<OrderInfo> orderList=orderInfoService.list(new QueryWrapper<OrderInfo>()
//				.inSql("sn", StrSplitUtils.in(sns))
//		);
        if (orderList != null) {
            System.out.println("size = " + orderList.size());
        }
        if (CollectionUtils.isEmpty(orderList)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        String paySN = ShopNoUtils.getPayOrderSn();
        Integer userId = null;
        BigDecimal fund = BigDecimal.ZERO;
        String companyNo = null;
        List<OrderPayment> saveOrderPaymentList = new ArrayList<OrderPayment>();
        List<OrderInfo> updateOrderList = new ArrayList<OrderInfo>();

        for (OrderInfo order : orderList) {
            if (PayStateEnum.Pay_Ing.getCode().equals(order.getPaymentState())) {
                throw new BusinessException(MallErrorEnum.Order_Pay_Ing);
            }
            if (PayStateEnum.Pay_Success.getCode().equals(order.getPaymentState())) {
                throw new BusinessException(MallErrorEnum.Order_Pay_Already);
            }
            if (!OrderStateEnum.OSE_Pay.getCode().equals(order.getStatus())) {
                throw new BusinessException(MallErrorEnum.Order_Pay_Ing);
            }
            if (userId == null) {
                userId = order.getUserId();
            } else {
                if (userId.intValue() != order.getUserId().intValue()) {
                    throw new BusinessException(MallErrorEnum.Order_NotOp_User);
                }
            }

            if (StringUtils.isEmpty(companyNo)) {
                companyNo = order.getMainCompanyNo();
            } else {

            }

            fund = fund.add(order.getFund());
            OrderPayment payment = new OrderPayment();
            payment.setType(PayActionTypeEnum.PA_Pay.getCode());
            payment.setPaySn(paySN);
            payment.setBizOrderType(bizOrderType);
            payment.setBizOrderSn(order.getSn());
            payment.setTotalFund(fund);
            payment.setCustNo(order.getCompanyNo());
            payment.setPayerUserId(order.getUserId());
            payment.setPaymentMethod(PayMethodEnum.PM_Online_Pay.getCode());
            payment.setPaymentChannel(paymentChannel);
            payment.setFund(order.getFund());
            payment.setFee(BigDecimal.ZERO);
            payment.setPaymentState(PayStateEnum.Pay_Ing.getCode());
            payment.setPaymentApplyDate(LocalDateTime.now());
            payment.setCheckState(YNEnum.NO.getCode());
            payment.addCreateParam(userInfo);
            saveOrderPaymentList.add(payment);

            order.setPaymentState(PayStateEnum.Pay_Ing.getCode());
            order.setPayDate(LocalDateTime.now());
            order.setPaymentFund(order.getFund());
            updateOrderList.add(order);
        }

        orderPaymentService.saveBatch(saveOrderPaymentList);
        orderInfoService.updateBatchById(updateOrderList);
        return shopOnlinePayService.payApply(companyNo, paySN, fund, paymentChannel, returnUrl, userInfo);
    }


    /**
     * 积分支付（单订单）
     */
    @Transactional
    @Override
    public void payByPoint(String sn, LoginSimpleUserInfo userInfo) {
        if (StringUtils.isEmpty(sn)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        List<String> sns = new ArrayList<String>();
        sns.add(sn);
        this.payByPoint(sns, IRelBusiType.Order_ObjType, userInfo);
    }

    /**
     * 积分支付（多订单）
     */
    @Transactional
    @Override
    public void payByPoint(List<String> sns, LoginSimpleUserInfo userInfo) {
        if (CollectionUtils.isEmpty(sns)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        this.payByPoint(sns, IRelBusiType.Order_ObjType, userInfo);
    }

    /**
     * 积分支付
     */
    public void payByPoint(List<String> sns, String bizOrderType, LoginSimpleUserInfo userInfo) {
        List<OrderInfo> orderList = orderInfoService.list(new QueryWrapper<OrderInfo>().in("sn", sns));
        if (CollectionUtils.isEmpty(orderList)) {
            return;
        }
        String paySN = ShopNoUtils.getPayOrderSn();
        Integer userId = null;
        String companyNo = null;
        BigDecimal fund = BigDecimal.ZERO;
        List<OrderPayment> saveOrderPaymentList = new ArrayList<OrderPayment>();
        List<OrderInfo> updateOrderList = new ArrayList<OrderInfo>();
        for (OrderInfo order : orderList) {
            if (!OrderStateEnum.OSE_Pay.getCode().equals(order.getStatus())) {
                throw new BusinessException(MallErrorEnum.Order_Pay_Ing);
            }
            if (!PayMethodEnum.PM_Point_Pay.getCode().equals(order.getPaymentMethod())) {
                throw new BusinessException(MallErrorEnum.Pay_Point_Unsupported);
            }
            if (userId == null) {
                userId = order.getUserId();
            } else {
                if (userId.intValue() != order.getUserId().intValue()) {
                    throw new BusinessException(MallErrorEnum.Order_NotOp_User);
                }
            }
            if (StringUtils.isEmpty(companyNo)) {
                companyNo = order.getMainCompanyNo();
            } else {

            }
            fund = fund.add(order.getFund());
            OrderPayment payment = new OrderPayment();
            payment.setType(PayActionTypeEnum.PA_Pay.getCode());
            payment.setPaySn(paySN);

            payment.setBizOrderType(bizOrderType);
            payment.setBizOrderSn(order.getSn());

            payment.setCustNo(order.getCompanyNo());
            payment.setPayerUserId(order.getUserId());
            payment.setPaymentMethod(PayMethodEnum.PM_Point_Pay.getCode());
            payment.setTotalFund(fund);
            payment.setFund(order.getFund());
            payment.setFee(BigDecimal.ZERO);
            payment.setPaymentState(PayStateEnum.Pay_Success.getCode());
            payment.setPaymentApplyDate(LocalDateTime.now());
            payment.setPaymentConfirmDate(LocalDateTime.now());
            payment.setMemo("积分支付");
            payment.setCheckState(YNEnum.YES.getCode());
            payment.setCheckDate(LocalDateTime.now());
            payment.setCheckUserId(userInfo.getId());
            payment.addCreateParam(userInfo);
            saveOrderPaymentList.add(payment);

            order.setStatus(OrderStateEnum.OSE_Send.getCode());
            order.setHandleDate(LocalDateTime.now());
            order.setHandleUserId(userInfo.getId());
            order.setPaymentMethod(payment.getPaymentMethod());
            order.setPaymentFee(payment.getFee());
            order.setPaymentFund(payment.getFund());
            order.setPaymentState(payment.getPaymentState());
            order.setPayDate(LocalDateTime.now());
            updateOrderList.add(order);
        }

        orderPaymentService.saveBatch(saveOrderPaymentList);
        orderInfoService.updateBatchById(updateOrderList);
        this._payByPoint(companyNo, paySN, userId, fund, userInfo);
    }

    /**
     * 积分支付
     */
    private void _payByPoint(String companyNo, String paySN, Integer userId, BigDecimal fund, LoginSimpleUserInfo userInfo) {
        AcctOpRequest pointParams = new AcctOpRequest();
        pointParams.setUserId(userId);
        pointParams.setType(AcctTypeEnum.Point_Acct.getCode());
        pointParams.setIsAcctDetail(YNEnum.YES.getCode());
        pointParams.setOpType(AcctOpTypeEnum.Sub_Acct.getCode());
        pointParams.setRelObjType(IRelBusiType.Order_Pay_ObjType);
        pointParams.setRelObjNo(paySN);
        pointParams.setFundOp(fund);
        pointParams.setFundTax(BigDecimal.ZERO);
        pointParams.setRelBizName("订单支付");
        pointParams.setRelDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        pointParams.setBusiType("支付");
        pointParams.setMemo("订单支付");
        pointParams.setOpUserId(userInfo.getId());
        pointParams.setOpIp(userInfo.getIp());
        BaseClientResult<String> payResp = accountRemoteService.opAcct(pointParams);
        CheckUtils.checkClientResult(payResp);
    }

    private void _payByBalance(String companyNo, String paySN, Integer userId, BigDecimal fund, LoginSimpleUserInfo userInfo) {
        if(userId!=0){
            AcctOpRequest pointParams = new AcctOpRequest();
            pointParams.setUserId(userId);
            pointParams.setType(AcctTypeEnum.Balance_Acct.getCode());
            pointParams.setIsAcctDetail(YNEnum.YES.getCode());
            pointParams.setOpType(AcctOpTypeEnum.Add_Acct.getCode());
            pointParams.setRelObjType(IRelBusiType.Order_Pay_ObjType);
            pointParams.setRelObjNo(paySN);
            pointParams.setFundOp(this.Percentage("80%", fund));
            pointParams.setFundTax(BigDecimal.ZERO);
            pointParams.setRelBizName("订单支付");
            pointParams.setRelDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pointParams.setBusiType("支付");
            pointParams.setMemo("订单支付");
            pointParams.setOpUserId(userInfo.getId());
            pointParams.setOpIp(userInfo.getIp());
            BaseClientResult<String> payResp = accountRemoteService.opAcct(pointParams);
            CheckUtils.checkClientResult(payResp);
        }
    }

    public BigDecimal Percentage(String pct, BigDecimal bigDecimal1) {
        pct = pct.replace("%", "");
        Float aFloat = Float.parseFloat(pct) / 100;
        BigDecimal bigDecimal = new BigDecimal(aFloat);
        BigDecimal multiply = bigDecimal1.multiply(bigDecimal);
        MathContext mathContext = new MathContext(3, RoundingMode.CEILING);
        return multiply.plus(mathContext);
    }

//	/**
//	 * 第三方支付
//	 * */
//	private PayApplyModel _pay(String companyNo, String sn,BigDecimal fund,PayChannelTypeEnum paymentChannel,LoginUserInfo userInfo) {
//		//todo:
//		//payRemoteService.
//		return  null;
//	}
//
//	


//	@Deprecated
//	private PayApplyModel payWxMini(String sn,BigDecimal fund,LoginUserInfo userInfo) {
//		try {
//			WXPay pay= WXPay.getInstall(wxPayConfig);
//			Map<String, String> payData=new HashMap<String, String>();
//			payData.put("body", "商品"); //商品描述
//			payData.put("out_trade_no", sn);//商户订单号
//			payData.put("total_fee", String.valueOf(fund.multiply(new BigDecimal(100)).intValue()));//标价金额 单位为分
//			payData.put("spbill_create_ip", userInfo.getIp());//终端IP
//			DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//			payData.put("time_start", df.format(LocalDateTime.now()));//交易起始时间  yyyyMMddHHmmss
//			payData.put("time_expire",  df.format(LocalDateTime.now().plusHours(1)));
//			payData.put("trade_type", PayChannelTypeEnum.WX_JSAPI.getCode());//交易类型 JSAPI--JSAPI支付（或小程序支付）、NATIVE--Native支付、APP--app支付，MWEB--H5支付
//			payData.put("openid", userInfo.getThirdOpenId());//用户标识
//			Map<String, String> payReturnData= pay.unifiedOrder(payData);
//			PayApplyModel data=new PayApplyModel(wxPayConfig,sn, fund,  payReturnData.get("prepay_id"));
//			return data;
//		} catch (Exception e) {
//			e.printStackTrace();
//			throw new BusinessException(ShopErrorEnum.Order_WX_Pay);
//		}
//	}


}
